import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../models/api_response.dart';
import '../models/page_result.dart';
import '../models/moment.dart';
import '../models/filter_data.dart';
import '../utils/http_client.dart';

class MomentService {
  // Debug模式和Release模式的baseUrl配置
  static const String _debugBaseUrl = 'http://localhost:18886';
  static const String _releaseBaseUrl = 'https://liufq.cn/api';

  // 根据运行模式自动切换baseUrl
  static String get baseUrl => kDebugMode ? _debugBaseUrl : _releaseBaseUrl;

  // API endpoints
  static const String _userLogin = '/user/login';
  static const String _momentsList = '/moments/list';
  static const String _momentsCreate = '/moments/create';
  static const String _momentsFilter = '/moments/filter';
  static const String _momentsRandom = '/moments/random';
  static String _momentsDetail(String id) => '/moments/$id';
  static String _momentsUpdate(String id) => '/moments/$id';
  static String _momentsDelete(String id) => '/moments/$id';

  final Function()? onUnauthorized;

  MomentService({this.onUnauthorized});
  Future<PageResult<Moment>> getMomentsList({
    int current = 1,
    int size = 20,
    String? tag,
    String? time,
    bool? isFavorite,
  }) async {
    try {
      final queryParams = <String, String>{
        'pageNo': current.toString(),
        'pageSize': size.toString(),
      };
      if (tag != null) queryParams['tag'] = tag;
      if (time != null) queryParams['time'] = time;
      if (isFavorite != null) queryParams['isFavorite'] = isFavorite.toString();

      final response = await HttpClient.get(
        _momentsList,
        queryParams: queryParams,
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse<PageResult<Moment>>.fromJson(
          jsonData,
          (data) => PageResult.fromJson(
            data as Map<String, dynamic>,
            (json) => Moment.fromJson(json),
          ),
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          return apiResponse.data!;
        } else {
          throw Exception(apiResponse.message);
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('获取列表失败: $e');
    }
  }

  Future<Moment> createMoment(String content, {String? title, String? createdTime}) async {
    try {
      final body = <String, dynamic>{'content': content};
      if (title != null && title.isNotEmpty) {
        body['title'] = title;
      }
      if (createdTime != null && createdTime.isNotEmpty) {
        body['createdTime'] = createdTime;
      }

      final response = await HttpClient.post(
        _momentsCreate,
        body: body,
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse<String>.fromJson(
          jsonData,
          (data) => data.toString(),
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          // 后端返回的是ID，需要重新获取详情
          final momentId = apiResponse.data!;
          return await getMomentDetail(momentId);
        } else {
          throw Exception(apiResponse.message);
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('创建失败: $e');
    }
  }

  Future<void> updateMoment(String id, String content, {String? title, String? createdTime}) async {
    try {
      final body = <String, dynamic>{'content': content};
      if (title != null && title.isNotEmpty) {
        body['title'] = title;
      }
      if (createdTime != null && createdTime.isNotEmpty) {
        body['createdTime'] = createdTime;
      }

      final response = await HttpClient.put(
        _momentsUpdate(id),
        body: body,
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final responseBody = utf8.decode(response.bodyBytes).trim();
        if (responseBody.isNotEmpty) {
          final jsonData = json.decode(responseBody);
          final apiResponse = ApiResponse.fromJson(jsonData, null);

          if (!apiResponse.isSuccess) {
            throw Exception(apiResponse.message);
          }
        }
        // 如果响应体为空，认为更新成功
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      // 如果是JSON解析错误但状态码是200，也认为更新成功
      if (e.toString().contains('FormatException')) {
        return;
      }
      throw Exception('更新失败: $e');
    }
  }

  Future<Moment> getMomentDetail(String id) async {
    try {
      final response = await HttpClient.get(
        _momentsDetail(id),
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse<Moment>.fromJson(
          jsonData,
          (data) => Moment.fromJson(data as Map<String, dynamic>),
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          return apiResponse.data!;
        } else {
          throw Exception(apiResponse.message);
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('获取详情失败: $e');
    }
  }

  Future<FilterData> getFilterData() async {
    try {
      final response = await HttpClient.get(
        _momentsFilter,
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse<FilterData>.fromJson(
          jsonData,
          (data) => FilterData.fromJson(data as Map<String, dynamic>),
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          return apiResponse.data!;
        } else {
          throw Exception(apiResponse.message);
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('获取筛选数据失败: $e');
    }
  }

  Future<void> deleteMoment(String id) async {
    try {
      final response = await HttpClient.delete(
        _momentsDelete(id),
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        // 检查响应体是否为空
        final responseBody = utf8.decode(response.bodyBytes).trim();
        if (responseBody.isNotEmpty) {
          final jsonData = json.decode(responseBody);
          final apiResponse = ApiResponse.fromJson(jsonData, null);

          if (!apiResponse.isSuccess) {
            throw Exception(apiResponse.message);
          }
        }
        // 如果响应体为空，认为删除成功
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      // 如果是JSON解析错误但状态码是200，也认为删除成功
      if (e.toString().contains('FormatException')) {
        return;
      }
      throw Exception('删除失败: $e');
    }
  }

  Future<void> updateFavorite(String id, bool isFavorite) async {
    try {
      final response = await HttpClient.put(
        _momentsUpdate(id),
        body: {'isFavorite': isFavorite},
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final responseBody = utf8.decode(response.bodyBytes).trim();
        if (responseBody.isNotEmpty) {
          final jsonData = json.decode(responseBody);
          final apiResponse = ApiResponse.fromJson(jsonData, null);

          if (!apiResponse.isSuccess) {
            throw Exception(apiResponse.message);
          }
        }
        // 如果响应体为空，认为更新成功
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      // 如果是JSON解析错误但状态码是200，也认为更新成功
      if (e.toString().contains('FormatException')) {
        return;
      }
      throw Exception('更新收藏状态失败: $e');
    }
  }

  Future<Moment> getRandomMoment() async {
    try {
      final response = await HttpClient.get(
        _momentsRandom,
        onUnauthorized: onUnauthorized,
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse<Moment>.fromJson(
          jsonData,
          (data) => Moment.fromJson(data as Map<String, dynamic>),
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          return apiResponse.data!;
        } else {
          throw Exception(apiResponse.message);
        }
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('获取随机内容失败: $e');
    }
  }
}
